<script setup lang="ts">
import {h} from 'vue';
import {Button, message, Modal as AntModal, Tag} from 'ant-design-vue';
import {useDrawer, useVxeGrid} from '#/ui-kit';
import {useDictStore} from '#/stores';
import dayjs from 'dayjs';

import {findRoleUserListPage, removeRoleUser} from '#/api/system/role';

const {getDictData} = useDictStore();

const [Drawer, drawerApi] = useDrawer({
  showCancelButton: false,
  showConfirmButton: false,
  destroyOnClose: true,
  onBeforeClose: () => {
    drawerApi.setData({});
  },
});

const [Grid, gridApi] = useVxeGrid({
  gridOptions: {
    columns: [
      {fixed: 'left', title: '#', type: 'seq', minWidth: 50},
      {fixed: 'left', field: 'nickname', title: '用户姓名', minWidth: 120,},
      {field: 'username', title: '用户账号', minWidth: 120,},
      {
        slots: {
          default: ({row}) => {
            const data = getDictData('enable_status', true).find((item) => item.value === row.enableStatus);
            return h(Tag, {color: data?.color || 'default'}, () => data?.label || '未知');
          }
        }, title: '启用状态', minWidth: 80,
      },
      {
        field: 'lastLoginTime', title: '最后登陆', minWidth: 180, formatter: ({cellValue}) => {
          return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '-';
        }
      },
      {field: 'createTime', title: '创建时间', formatter: 'formatDateTime', minWidth: 180},
      {fixed: 'right', slots: {default: 'action'}, title: '操作', minWidth: 120},
    ],
    proxyConfig: {
      ajax: {
        query: async ({page}, formValues) => {
          return await getRoleUserListPage({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        }
      }
    },
    stripe: true,
    keepSource: true,
    height: 'auto',
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  },
  formOptions: {
    commonConfig: {
      componentProps: {
        allowClear: true,
      },
    },
    schema: [
      {
        label: '用户姓名',
        fieldName: 'nickname',
        component: 'Input',
        componentProps: {
          placeholder: '请输入用户姓名'
        }
      },
      {
        label: '用户账号',
        fieldName: 'username',
        component: 'Input',
        componentProps: {
          placeholder: '请输入用户账号'
        }
      },
      {
        label: '启用状态',
        fieldName: 'enableStatus',
        component: 'Select',
        componentProps: {
          options: getDictData('enable_status', true),
          placeholder: '请选择启用状态'
        }
      },
    ],
    showCollapseButton: true,
    collapsed: true,
  }
});

const getRoleUserListPage = async (params) => {
  params.roleId = drawerApi?.getData()?.id;
  return new Promise<{ items: any; total: number }>((resolve) => {
    findRoleUserListPage(params).then(res => {
      resolve({
        items: res.records,
        total: res.totalRow,
      });
    }).catch(() => {
      resolve({
        items: [],
        total: 0,
      });
    })
  });
}

const handleRoleUser = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否删除当前角色关联用户',
    centered: true,
    async onOk() {
      await removeRoleUser({roleId: drawerApi.getData()?.id, userId: row?.id}).then(() => {
        message.success('角色关联用户删除成功');
        gridApi.reload();
      });
    }
  })
}
</script>

<template>
  <Drawer>
    <Grid>
      <template #action="{ row }">
        <Button type="link" size="small" v-access:code="['sys:role:remove-user']" @click="handleRoleUser(row)">删除
        </Button>
      </template>
    </Grid>
  </Drawer>
</template>